const mysql = require('mysql2/promise');
const config = require('./config');

let pool;

async function init(dbConfig) {
  // 创建连接池
  pool = mysql.createPool(dbConfig);
  
  // 创建新闻表
  await pool.query(`
    CREATE TABLE IF NOT EXISTS news (
      id INT AUTO_INCREMENT PRIMARY KEY,
      title VARCHAR(255) NOT NULL,
      content TEXT,
      publish_time DATETIME,
      source_url VARCHAR(255),
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
  `);
  
  // 创建图片表
  await pool.query(`
    CREATE TABLE IF NOT EXISTS images (
      id INT AUTO_INCREMENT PRIMARY KEY,
      news_id INT,
      url VARCHAR(255),
      local_path VARCHAR(255),
      FOREIGN KEY (news_id) REFERENCES news(id)
    )
  `);
}

async function saveNews(newsList) {
  for (const news of newsList) {
    const [result] = await pool.query(
      'INSERT INTO news (title, content, publish_time, source_url) VALUES (?, ?, ?, ?)',
      [news.title, news.content, news.publishTime, news.sourceUrl]
    );
    
    // 保存图片信息
    if (news.images && news.images.length > 0) {
      for (const image of news.images) {
        await pool.query(
          'INSERT INTO images (news_id, url, local_path) VALUES (?, ?, ?)',
          [result.insertId, image.url, image.localPath]
        );
      }
    }
  }
}

async function close() {
  if (pool) {
    await pool.end();
  }
}

module.exports = {
  init,
  saveNews,
  close
};
